package com.galeno.练习

import org.apache.spark.rdd.RDD
import org.apache.spark.rdd.RDD.rddToOrderedRDDFunctions
import org.apache.spark.{SparkConf, SparkContext}

import java.util.Comparator

/**
 * @Title: ${file_name}
 * @Description: ${todo}
 * @author galeno
 * @date 2021/8/2619:43
 */
object SortByKey练习 {
  def main(args: Array[String]): Unit = {
    val sc = new SparkContext(new SparkConf().setMaster("local").setAppName("练习1"))
    val rddPerson: RDD[Person] = sc.makeRDD(Seq(
      new Person("张嘉俊", 23, "广东"),
      new Person("王兴国", 24, "广东"),
      new Person("郑格非", 22, "福建"),
      new Person("郝瑞瑞", 21, "福建"),
      new Person("柳坤坤", 25, "辽宁"),
      new Person("李宗文", 32, "辽宁")))
    val rdd1: RDD[((String, Int), String)] = rddPerson.map(x => ((x.name, x.age), x.province)).sortByKey(true, 2)
    rdd1.saveAsTextFile("dataout/text1")









    val comp: Comparator[Person] with Object {
      def compare(o1: Person, o2: Person): Int
    } = new Comparator[Person] {
      override def compare(o1: Person, o2: Person): Int = {
        var res = 0;
        res = o1.name.compare(o2.name)
        if (res == 0) {
          res = o1.age.compare(o2.age)
        }
        if (res == 0) {
          res = o1.province.compare(o2.province)
        }
        res
      }
    }

  }


}

case class Person(name: String, age: Int, province: String) extends Ordering[Person]with Ordered[Person] with Comparable[Person]{
  override def compare(x: Person, y: Person): Int = {
    var res = 0;
    res = x.name.compare(y.name)
    if (res == 0) {
      res = x.age.compare(y.age)
    }
    if (res == 0) {
      res = x.province.compare(y.province)
    }
    res
  }

  override def compare(that: Person): Int = {
    var res = 0;
    res = this.name.compare(that.name)
    if (res == 0) {
      res = this.age.compare(that.age)
    }
    if (res == 0) {
      res = this.province.compare(that.province)
    }
    res

  }
}
